package com.tree.common.interceptor;

import com.tree.common.util.TraceContextHolder;
import com.tree.common.util.UserContextHolder;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.slf4j.MDC;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.UUID;

/**
 * @ClassName com.demo.common.interceptor
 * Description: <类功能描述>. <br>
 * <p>
 * <使用说明>
 * </p>
 * @Author tree
 * @Date 2019-05-25 23:16
 * @Version 1.0
 */
@Slf4j
public class TraceInterceptor extends BaseInterceptor{


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        try {
            generateTraceId();
        }catch (Exception e){
            log.warn("set trace id for per request");
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        super.postHandle(request, response, handler, modelAndView);
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        try{
            MDC.clear();
            UserContextHolder.destroy();
            TraceContextHolder.remove();
        }catch (Exception e){
            log.error("[afterCompletion],TraceInterceptor exception",e);
        }
    }

    public void generateTraceId(){
        String traceId = UUID.randomUUID().toString();
        MDC.put("traceId",traceId);
        TraceContextHolder.setCurrentTraceId(traceId);

    }

}
